package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.config.CardPosterConfig;
import one.stand.entity.ImageEntity;
import one.stand.entity.PosterEntity;
import one.stand.entity.WxNoticeEntity;
import one.stand.entity.websocket.CompanyInfoEntity;
import one.stand.enums.*;
import one.stand.model.*;
import one.stand.request.*;
import one.stand.response.BusinessCardResponse;
import one.stand.response.GetCompanyStaffResponse;
import one.stand.response.UserCommonResponse;
import one.stand.service.*;
import one.stand.util.ImageGenerateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
public class BusinessCardServiceImpl extends PublicBaseService implements BusinessCardService {

    @Autowired
    protected CardPosterConfig cardPosterConfig;

    @Autowired
    protected WxMessageService wxMessageService;
    @Autowired
    protected WxSunCodeService wxSunCodeService;
    @Autowired
    protected CompanyAccontService companyAccontService;
    @Autowired
    protected PosterService posterService;
    /**
     * crm端查询名片列表
     *
     * @param request
     * @return
     */
    @Override
    public ResultModel<List<BusinessCardResponse>> selectBusinessCardList(BusinessCardRequest request) {
        if(request == null){
            return ResultModel.checkParamFail();
        }

        return null;
    }

    @Override
    public ResultModel<Boolean> updateCardWelcomeSpeech(BusinessCardRequest request) {
        log.info("修改用户名片欢迎语:{}",JSON.toJSONString(request));
        if(request == null){
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setCardId(request.getMyCardId());
        model.setWelcomeSpeech(request.getWelcomeSpeech());
        model.setShareSpeech(request.getShareSpeech());
        businessCardMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    /**
     * 审核名片
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> auditBusinessCard(BusinessCardRequest request) {
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        // 查询公司购买服务数
        CompanyServiceModel companyServiceModel = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCId().intValue());
            setType(1);
        }});
        if (companyServiceModel == null || companyServiceModel.getAvailableNum() <= 0) {
            return ResultModel.fail("可用名片数不足，请前去购买服务名片数~！");
        }
        // 修改名片状态
        BusinessCardModel model = new BusinessCardModel();
        model.setCardId(request.getCardId());
        model.setAuditState(request.getAuditState());
        model.setAuditRemark(request.getAuditRemark());
        r = businessCardMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            Integer serviceId = companyServiceModel.getServiceId();
            // 审核同意，更新公司购买名片服务记录
            if (request.getAuditState().equals(AuditStateEnums.APPLY_SUCCESS.getCode())) {
                companyServiceModel.setServiceId(null);
                companyServiceModel.setAvailableNum(companyServiceModel.getAvailableNum() - 1);
                companyServiceModel.setCreateTime(currentDate());
                r = companyServiceMapper.insertSelective(companyServiceModel);
                if(r > 0){
                    // 修改之前的名片服务记录表为记录
                    companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel(){{
                        setType(0);
                        setServiceId(serviceId);
                    }});
                }
            }
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Map<String, Object>> getCompanyStaffList(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        model.setCompanyId(request.getCId().intValue());
        model.setName(request.getName());
        List<GetCompanyStaffResponse> responseList = businessCardMapper.getCompanyStaffList(model);
        PageInfo<GetCompanyStaffResponse> pageInfo = new PageInfo(responseList);
        Map<String, Object> map = new HashMap<>(2);
        // 数据
        map.put("list", pageInfo.getList());
        // 人数
        map.put("totalNumber", pageInfo.getTotal());
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<GetCompanyStaffResponse> getCompanyStaffInfo(BusinessCardRequest request) {
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        model.setUserId(request.getId().intValue());
        model.setCardId(request.getCardId());
        List<GetCompanyStaffResponse> responseList = businessCardMapper.getCompanyStaffList(model);
        if(responseList == null || responseList.size() <= 0){
            return ResultModel.noData();
        }
        return ResultModel.success(responseList.get(0));
    }

    @Override
    public ResultModel<Integer> manualAdd(BusinessCardRequest request) {

        if (StringUtils.isEmpty(request.getPhone()) && StringUtils.isEmpty(request.getPersonalWx())) {
            return ResultModel.fail("请输入手机号码~!");
        }
        BusinessCardModel cardModel = new BusinessCardModel();
        BeanUtils.copyProperties(request, cardModel);
        cardModel.setCreateTime(currentDate());
        cardModel.setType(2);
        cardModel.setStyle(1);
        if (businessCardMapper.insertSelective(cardModel) > 0) {
            return ResultModel.success(cardModel.getCardId());
        }
        return ResultModel.fail();
    }

    @Autowired
    private FollowRecordService followRecordService;

    @Override
    public ResultModel updAdd(BusinessCardRequest request) {
        BusinessCardModel model = businessCardMapper.getCardPhone(new BusinessCardModel(){{
            setCardId(request.getCardId());
            setIsDel(0);
            setState(2);
        }});
        if(model == null){
            return ResultModel.fail();
        }
        // 电话不同就添加跟进记录
        log.info("修改客户：电话号码由[{}]变成[{}]",model.getPhone(),request.getPhone());
        if(!(model.getPhone() + "").equals(request.getPhone() + "")){
            JSONObject jsonObject = new JSONObject();
            StringBuffer data = new StringBuffer("电话号码由[");
            data.append(StringUtils.isBlank(model.getPhone()) ? "空" : model.getPhone());
            data.append("]变为[");
            data.append(StringUtils.isBlank(request.getPhone()) ? "空" : request.getPhone());
            data.append("]");
            jsonObject.put("data", data);
            jsonObject.put("type", 5);
            FollowRecordRequest recordRequest = new FollowRecordRequest();
            recordRequest.setCardId(request.getCardId());
            recordRequest.setId(request.getId());
            recordRequest.setFollowRemark(jsonObject.toJSONString());
            recordRequest.setMyCardId(request.getMyCardId());
            recordRequest.setFollowType(6);
            followRecordService.addFollow(recordRequest);
        }
        BusinessCardModel cardModel = new BusinessCardModel();
        BeanUtils.copyProperties(request, cardModel);
        if (businessCardMapper.updateByPrimaryKeySelective(cardModel) > 0) {
            return ResultModel.success();
        }
        return ResultModel.fail();

    }

    @Override
    public ResultModel<List<BusinessCardResponse>> getList(BusinessCardRequest request) {
        BusinessCardModel model = new BusinessCardModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        model.setIsDel(0);
        model.setState(1);
        List<BusinessCardModel> modelList = businessCardMapper.selectList(model);
        List<BusinessCardResponse> responseList = new ArrayList<>();
        modelList.forEach(m -> {
            BusinessCardResponse response = new BusinessCardResponse();
            BeanUtils.copyProperties(m, response);
            responseList.add(response);
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel getCompanyUserInfo(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = new BusinessCardModel();
        if (request.getCardId() != null) {
            model = businessCardMapper.selectByPrimaryKey(request.getCardId());
        } else if (request.getUserId() != null) {
            model = businessCardMapper.select(new BusinessCardModel() {{
                setUserId(request.getUserId());
                setIsDel(0);
                setState(1);
            }});
            if(model == null){
                model = new BusinessCardModel();
                UserModel userModel =userMapper.select(new UserModel(){{
                    setUserId(request.getUserId().longValue());
                    setIsDel(0);
                }});
                if(userModel != null) {
                    model.setName(userModel.getNickeName() == null ? "" : new String(java.util.Base64.getDecoder().decode(userModel.getNickeName())));
                    model.setNickeName(userModel.getNickeName() == null ? "" : new String(java.util.Base64.getDecoder().decode(userModel.getNickeName())));
                    model.setPhone(userModel.getPhone());
                    model.setLogo(userModel.getAvatarUrl());
                }
            }
        } else if (request.getMyCardId() != null) {
            // crm端查询个人中心名片信息
            model = businessCardMapper.selectByPrimaryKey(request.getMyCardId().intValue());
            if(model != null){
                model.setBrowsePhoto(businessCardMapper.getBrowsePhoto(model.getCardId()));
                BusinessCardModel businessCardModel = businessCardMapper.selectCrmPersonalData(model.getCardId());
                if(businessCardModel != null) {
                    model.setPerfectRate(businessCardModel.getPerfectRate());
                    model.setPerfectRateRank(businessCardModel.getPerfectRateRank());
                    model.setYesterdayCustomerCount(businessCardModel.getYesterdayCustomerCount());
                    model.setYesterdayOrderCount(businessCardModel.getYesterdayOrderCount());
                    model.setYesterdaySeeCount(businessCardModel.getYesterdaySeeCount());
                }
            }
        }
        return ResultModel.success(model);
    }

    @Override
    public ResultModel<CompanyInfoEntity> messageGetCompanyInfo(Long cardId) {
        return ResultModel.success(businessCardMapper.getCompanyInfo(cardId));
    }

    @Override
    public ResultModel getWxTwoCode(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel model = businessCardMapper.select(new BusinessCardModel() {{
            setCardId(request.getCardId());
            setState(1);
        }});
        if (StringUtils.isBlank(model.getWxTwoCode())) {

            String twoCode = posterService.getWxCode(request.getCardId().toString(), model.getCompanyId().toString());
            if (twoCode != null) {
                return ResultModel.success(twoCode);
            }
            return ResultModel.fail();
        }
        return ResultModel.success(model.getWxTwoCode());
    }


    @Override
    public ResultModel getCardPoster(BusinessCardRequest request) {
        return posterService.getCardPoster(request);
    }

    /**
     * 发送给user端的客戶
     *
     * @param sendUserId 发送人userId
     * @param text       聊天消息提示內容
     * @param type       0未读消息提示，1联系方式提示
     * @return
     */
    @Override
    public ResultModel unreadMessage(Integer sendUserId, Integer receiveUserId, String text, Integer type) {
        // 微信推送 未读消息
        WxNoticeEntity entity = userMapper.getSendTemplateInfo(sendUserId, receiveUserId,2);
        if (SendTypeEnum.CONTACT_US.getCode().equals(type)) {
            text = "已向你发送了联系方式，尽快与他联系~!";
        }
        String[] arr = {entity.getNickeName(), getDay(), text};

        wxMessageService.sendTemplate(entity.getUserOpenId(), entity.getUserFormId(), WxNoticeEnums.UNREAD_MESSAGE_USER.getCode(), arr, LoginEnum.USER.getAccountType(),entity.getCompanyId());
        return ResultModel.success();
    }

    @Override
    public ResultModel<BusinessCardResponse> getCardPhone(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }
        BusinessCardModel map = businessCardMapper.getCardPhone(new BusinessCardModel() {{
            setUserId(request.getUserId());
            setState(1);
            setIsDel(0);
        }});
        BusinessCardResponse response = new BusinessCardResponse();
        BeanUtils.copyProperties(map, response);

        return ResultModel.success(response);
    }

    /**
     * 验证名片是否过期
     *
     * @param request
     * @return
     */
    @Override
    @Cacheable(value = RedisCode.REDIS_DB_CACHE,key = "#root.targetClass.toString()+'.'+#root.methodName+':'+#request.toString()")
    public ResultModel<Long> verifyExpired(BusinessCardRequest request) {
        if (request == null || request.getCardId() == null) {
            return ResultModel.checkParamFail();
        }
        CompanyServiceModel model = companyServiceMapper.verifyExpired(new CompanyServiceModel() {{
            setCardId(request.getCardId());
        }});
        if(model == null || model.getEndTime() == null){
            return ResultModel.fail("暂无名片服务~!");
        }
        Long day = days(model.getEndTime());
        if(day < 0){
            return ResultModel.fail("名片已过期~!");
        }
        return ResultModel.success(day);
    }

    @Override
    public ResultModel<Integer> formIdCount(BusinessCardRequest request) {
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        userMapper.delFormId("");
        Map<String, String> map = new HashMap<>(2);
        map.put("userId",request.getId().toString());
        map.put("type","2");
        Integer num = userMapper.formIdCount(map);
        return ResultModel.success(num);
    }

    @Override
    public ResultModel<Boolean> delFormId(BusinessCardRequest request) {
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        Map<String, String> map = new HashMap<>(2);
        map.put("userId",request.getId().toString());
        map.put("type","2");
        userMapper.delUserFormId(map);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<List<UserCommonResponse>> selectUserCommonList(UserCommonRequest request) {
        if(request == null || request.getMyCardId() == null || request.getId() == null || request.getType() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        if(NumberEnum.ONE.getCode().equals(request.getType())){
            model.setUserId(request.getId().intValue());
            model.setType(request.getType());
        }else if(NumberEnum.TWO.getCode().equals(request.getType())){
            model.setCardId(request.getMyCardId());
            model.setType(request.getType());
        }
        List<UserCommonModel> list = userCommonMapper.select(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        List<UserCommonResponse> responseList = new ArrayList<>();
        list.forEach(obj->{{
            UserCommonResponse response = new UserCommonResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<Boolean> insertUserCommonList(UserCommonRequest request) {
        if(request == null || request.getMyCardId() == null || StringUtils.isBlank(request.getText())){
            return ResultModel.checkParamFail();
        }
        UserCommonModel userCommonModel = new UserCommonModel();
        if(NumberEnum.ONE.getCode().equals(request.getType())){
            userCommonModel.setUserId(request.getId().intValue());
            userCommonModel.setType(request.getType());
        }else if(NumberEnum.TWO.getCode().equals(request.getType())){
            userCommonModel.setCardId(request.getMyCardId());
            userCommonModel.setType(request.getType());
        }
        if(userCommonMapper.selectCount(userCommonModel) > 12){
            return ResultModel.fail("常用语不能超过12条~！");
        }
        UserCommonModel model = new UserCommonModel();
        model.setText(request.getText());
        if(request.getCommonId() == null) {
            if(NumberEnum.ONE.getCode().equals(request.getType())){
                model.setUserId(request.getId().intValue());
                model.setType(request.getType());
            }else if(NumberEnum.TWO.getCode().equals(request.getType())){
                model.setCardId(request.getMyCardId());
                model.setType(request.getType());
            }
            model.setIsDel(0);
            model.setCreateTime(currentDate());
            model.setSort(userCommonMapper.getMaxSort(new UserCommonModel(){{
                if(NumberEnum.ONE.getCode().equals(request.getType())){
                    setUserId(request.getId().intValue());
                    setType(request.getType());
                }else if(NumberEnum.TWO.getCode().equals(request.getType())){
                    setCardId(request.getMyCardId());
                    setType(request.getType());
                }
            }}) + 1);
            userCommonMapper.insertSelective(model);
            return ResultModel.success(true);
        }
        model.setCommonId(request.getCommonId());
        userCommonMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> delUserCommonList(UserCommonRequest request) {
        if(request == null || request.getCommonId() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        model.setIsDel(1);
        model.setCommonId(request.getCommonId());
        userCommonMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> moveUserCommon(UserCommonRequest request) {
        if(request == null || request.getCommonId() == null || request.getMoveType() == null || request.getMyCardId() == null){
            return ResultModel.checkParamFail();
        }
        UserCommonModel model = new UserCommonModel();
        model.setCommonId(request.getCommonId());
        model.setMoveType(request.getMoveType());
        if(NumberEnum.ONE.getCode().equals(request.getType())){
            model.setUserId(request.getId().intValue());
            model.setType(request.getType());
        }else if(NumberEnum.TWO.getCode().equals(request.getType())){
            model.setCardId(request.getMyCardId());
            model.setType(request.getType());
        }
        UserCommonModel userCommonModel = userCommonMapper.selectThanSort(model);
        if(userCommonModel == null){
            if(ONE.equals(request.getMoveType())){
                return ResultModel.fail("到顶了，无法上移！");
            }else if(TWO.equals(request.getMoveType())){
                return ResultModel.fail("到底了，无法下移！");
            }
        }
        // 修改排序
        model.setSort(userCommonModel.getSort());
        if(userCommonMapper.updateByPrimaryKeySelective(model) > 0){
            model = new UserCommonModel();
            model.setCommonId(userCommonModel.getCommonId());
            model.setSort(userCommonModel.getLastSort());
            userCommonMapper.updateByPrimaryKeySelective(model);
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

}
